
/**
 * 等待节点出现一次
 * @param selector
 * @param callback
 */
let appear = false
function observe(selector, callback) {
    /**
     * dom 操作的监听
     * @param mutationList
     */
    let observerCallback = function (mutationList) {
        mutationList.forEach(function (mutation) {

            // 如果不是新增 node 的操作, 或者已经出现过, 那么直接 return
            if (!mutation.addedNodes || appear) return

            // 遍历插入的节点数组
            //for (let node of mutation.addedNodes) {
                // do things to your newly added nodes here
                // console.log(node)

                // 如果有节点, 那么执行 callback 函数
                if (document.querySelector(selector)) {
                    appear = true
                    callback()
                }
            //}
        })
    }
    /**
     * 观察者模式, 监听 dom 树修改
     * https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
     * https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists
     * @type {MutationObserver}
     */
    let observer = new MutationObserver(observerCallback)

    observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
    })

    // 暂停接收通知
    // observer.disconnect()
    // 继续观察
    // observer.observe()
}

// https://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate
// 劫持 history, 当操作 history.pushState 时, 会先执行我们的代码 history.onpushstate
(function (history) {
    let pushState = history.pushState;
    history.pushState = function (state) {
        if (typeof history.onpushstate === "function") {
            // 自定义的回调事件
            history.onpushstate({state: state});
        }
        // ... whatever else you want to do
        // maybe call onhashchange e.handler
        return pushState.apply(history, arguments);
    };
})(window.history);

// https://developer.mozilla.org/zh-CN/docs/Web/API/Window/onpopstate
// history.onpushstate 是我们自定义的函数
// window.onpopstate    popstate 事件只会在浏览器某些行为下触发, 比如点击后退, 前进按钮 (或者在 JavaScript 中调用 history.back()、history.forward()、history.go() 方法), 此外, a 标签的锚点也会触发该事件.    调用 history.pushState() 或者 history.replaceState() 不会触发 popstate 事件.
window.onpopstate = history.onpushstate = () => {
    console.log('pushed...');
    // 判断是否存在 window.push 函数
    // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof
    if (typeof window.push === "function") {
        // 自定义的回调函数
        window.push()
    }
};

/*
HashChangeEvent
    oldURL: "http://family.okjiaoyu.cn/#/"
    newURL: "http://family.okjiaoyu.cn/#/testDoc/testDoc"
    type: "hashchange"
 */
// vue 是调用 history.pushState / history.replaceState, 不会触发 hashchange
// 点击触发
window.addEventListener('hashchange', history.onpushstate, false);
